package com.ruoyi.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

/**
 * 文件工具类
 *
 * @author Mr-Le
 */
public class FileTool {

    /**
     * 将file转换成fileItem
     *
     * @param file
     * @param fieldName
     * @return
     */
    public static FileItem getMultipartFile(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 通过URL下载图片
     *
     * @param url      图片链接
     * @param dir      保存目录
     * @param fileName 保存文件名
     * @return 保存图片状态
     */
    public static boolean downloadImageByUrl(String url, String dir, String fileName) {
        boolean image = false;
        try {
            File localFile = getAbsoluteFile(dir, fileName);
            image = downloadImage(url, "JPEG", localFile);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return image;
    }

    /**
     * 获取文件，通过路径，没有文件就创建文件
     *
     * @param saveDir  保存路径
     * @param fileName 文件名
     * @return 返回文案类型
     * @throws IOException IO操作异常
     */
    private static final File getAbsoluteFile(String saveDir, String fileName) throws IOException {
        File desc = new File(saveDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }


    private static boolean downloadImage(String imageUrl, String formatName, File localFile) {
        boolean isSuccess = false;
        URL url = null;
        try {
            url = new URL(imageUrl);
            isSuccess = ImageIO.write(ImageIO.read(url), formatName, localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }
}
